<template>
  <div class="min-h-screen bg-gray-50 relative">
    <!-- 导航栏 -->
    <AppHeader :show-back-button="false" :show-nav-menu="false" :show-breadcrumb="true" :show-location="false"
      :show-search-button="false" :show-notification-button="false" :show-decorations="false" logo-size="medium"
      :current-page-title="product?.name || '产品详情'" :breadcrumb-items="[
        { label: '首页', path: '/' },
        { label: '产品中心', path: '/products' },
        { label: product?.name || '产品详情' }
      ]" />

    <!-- 主要内容 -->
    <div class="container mx-auto px-6 py-8 relative" v-if="product && !loading && !error">
      <div class="grid lg:grid-cols-2 gap-12 mb-12">
        <!-- 左侧：产品图片和特性 -->
        <div class="space-y-6">
          <!-- 产品图片展示 -->
          <div class="bg-white rounded-2xl border border-gray-200 shadow-lg overflow-hidden">
            <div class="relative h-96 bg-gray-50 p-6">
              <!-- 产品图片或placeholder -->
              <div v-if="product.image" class="product-image-container">
                <img :src="product.image" :alt="product.name"
                  class="w-full h-full object-contain transition-all duration-500 hover:scale-105"
                  @error="$event.target.style.display = 'none'">
              </div>
              <div v-else class="product-placeholder">
                <div class="product-icon-wrapper">
                  <i class="bi bi-cpu text-6xl text-blue-500"></i>
                </div>
                <span class="product-placeholder-text text-gray-700 mt-4">{{ product.name }}</span>
              </div>

              <!-- 折扣标签 -->
              <div v-if="product.originalPrice && product.originalPrice > product.price"
                class="absolute top-4 left-4 bg-red-500 text-white px-4 py-2 rounded-full text-sm font-bold shadow-lg">
                <i class="bi bi-lightning-fill mr-1"></i>
                省 ¥{{ (product.originalPrice - product.price).toLocaleString() }}
              </div>

              <!-- 库存状态 -->
              <div class="absolute top-4 right-4">
                <span v-if="!product.inStock"
                  class="inline-flex items-center px-4 py-2 rounded-full text-sm font-semibold bg-red-100 text-red-700 border border-red-200">
                  <i class="bi bi-x-circle-fill mr-2"></i>缺货
                </span>
                <span v-else-if="product.stockCount <= 5"
                  class="inline-flex items-center px-4 py-2 rounded-full text-sm font-semibold bg-orange-100 text-orange-700 border border-orange-200">
                  <i class="bi bi-exclamation-triangle-fill mr-2"></i>仅剩 {{ product.stockCount }} 件
                </span>
                <span v-else
                  class="inline-flex items-center px-4 py-2 rounded-full text-sm font-semibold bg-green-100 text-green-700 border border-green-200">
                  <i class="bi bi-check-circle-fill mr-2"></i>现货充足
                </span>
              </div>

              <!-- 产品类型标识 -->
              <div class="absolute bottom-4 left-4">
                <span class="inline-flex items-center px-3 py-1 rounded-lg text-xs font-medium bg-blue-100 text-blue-700 border border-blue-200">
                  <i class="bi bi-bookmark-fill mr-1"></i>
                  {{ getProductCategory(product.category) }}
                </span>
              </div>
            </div>
          </div>

          <!-- 产品特性 -->
          <div class="bg-white rounded-2xl border border-gray-200 shadow-lg p-8">
            <h3 class="text-2xl font-bold text-gray-900 mb-6 flex items-center gap-3">
              <div class="p-2 bg-blue-100 rounded-lg">
                <i class="bi bi-stars text-blue-600"></i>
              </div>
              <span>核心特性</span>
            </h3>
            <div class="grid grid-cols-1 gap-4" v-if="product.features && product.features.length > 0">
              <div v-for="(feature, index) in product.features" :key="feature"
                class="group flex items-center gap-4 p-4 bg-gray-50 rounded-xl border border-gray-100 hover:border-blue-200 hover:bg-blue-50 transition-all duration-300"
                :style="{ 'animation-delay': `${index * 100}ms` }">
                <div class="flex-shrink-0 w-8 h-8 bg-green-500 rounded-full flex items-center justify-center group-hover:scale-110 transition-transform duration-300">
                  <i class="bi bi-check text-white text-sm font-bold"></i>
                </div>
                <span class="text-gray-900 font-medium group-hover:text-blue-700 transition-colors duration-300">{{ feature.title }}</span>
              </div>
            </div>
            <div v-else class="text-center py-8">
              <i class="bi bi-info-circle text-3xl mb-2 text-gray-400"></i>
              <p class="text-gray-500">暂无特性信息</p>
            </div>
          </div>
        </div>

        <!-- 右侧：产品信息和购买 -->
        <div class="space-y-6">
          <!-- 基本信息 -->
          <div class="bg-white rounded-2xl border border-gray-200 shadow-lg p-8">
            <!-- 品牌和收藏 -->
            <div class="flex items-center justify-between mb-6">
              <div class="flex items-center gap-4">
                <span class="inline-flex items-center px-5 py-2 rounded-xl text-sm font-bold bg-blue-100 text-blue-700 border border-blue-200">
                  <i class="bi bi-award mr-2"></i>
                  {{ product.brand }}
                </span>
                <div class="flex items-center gap-2 text-sm text-gray-500">
                  <i class="bi bi-eye text-blue-500"></i>
                  <span>{{ product.viewCount || 1234 }} 次浏览</span>
                </div>
              </div>
              <button @click="toggleFavorite" :class="[
                'p-3 rounded-xl border transition-all duration-300 group relative overflow-hidden',
                isFavorite
                  ? 'bg-red-50 border-red-200 text-red-600'
                  : 'border-gray-200 text-gray-400 hover:border-red-200 hover:text-red-600 hover:bg-red-50'
              ]">
                <i :class="isFavorite ? 'bi bi-heart-fill' : 'bi bi-heart'"
                  class="text-xl relative z-10 group-hover:scale-110 transition-transform duration-300"></i>
              </button>
            </div>

            <!-- 产品名称 -->
            <h1 class="text-4xl font-bold text-gray-900 mb-4 leading-tight">
              {{ product.name }}
            </h1>

            <!-- 产品型号和SKU -->
            <div class="flex items-center gap-4 mb-6 text-gray-500">
              <span v-if="product.model" class="text-sm">
                <i class="bi bi-tag mr-1"></i>
                型号: {{ product.model }}
              </span>
              <span v-if="product.sku" class="text-sm">
                <i class="bi bi-upc mr-1"></i>
                SKU: {{ product.sku }}
              </span>
            </div>

            <!-- 评分展示 -->
            <div class="flex items-center gap-6 mb-8 p-4 bg-gray-50 rounded-xl border border-gray-100">
              <div class="flex items-center gap-3">
                <div class="flex">
                  <i v-for="i in 5" :key="i" :class="i <= product.rating ? 'text-yellow-400' : 'text-gray-300'"
                    class="bi bi-star-fill text-xl"></i>
                </div>
                <span class="text-2xl font-bold text-gray-900">{{ product.rating }}</span>
              </div>
              <div class="h-8 w-px bg-gray-300"></div>
              <div class="flex items-center gap-2 text-gray-600">
                <i class="bi bi-chat-dots text-blue-500"></i>
                <span>{{ product.reviewCount }} 条评价</span>
              </div>
              <div class="flex items-center gap-2 text-gray-600">
                <i class="bi bi-truck text-green-500"></i>
                <span>免费配送</span>
              </div>
              <div class="flex items-center gap-2 text-gray-600">
                <i class="bi bi-graph-up text-purple-500"></i>
                <span>销量 {{ product.sales }}</span>
              </div>
            </div>

            <!-- 价格展示 -->
            <div class="mb-8 p-6 bg-blue-50 rounded-xl border border-blue-100">
              <div class="flex items-end gap-4 mb-3">
                <span class="text-5xl font-bold text-blue-600">
                  ¥{{ product.price.toLocaleString() }}
                </span>
                <span v-if="product.originalPrice && product.originalPrice > product.price"
                  class="text-2xl text-gray-500 line-through mb-2">
                  ¥{{ product.originalPrice.toLocaleString() }}
                </span>
                <span v-if="product.originalPrice && product.originalPrice > product.price"
                  class="px-3 py-1 bg-red-100 text-red-700 rounded-lg text-sm font-medium border border-red-200 mb-2">
                  省{{ Math.round(((product.originalPrice - product.price) / product.originalPrice) * 100) }}%
                </span>
              </div>
              <p class="text-gray-700">{{ product.description }}</p>
            </div>

            <!-- 数量选择 -->
            <div class="mb-8">
              <label class="block text-sm font-bold text-gray-900 mb-4 flex items-center gap-2">
                <i class="bi bi-123 text-blue-500"></i>
                购买数量
              </label>
              <div class="flex items-center gap-6">
                <div class="flex items-center border border-gray-300 rounded-xl bg-white">
                  <button @click="decreaseQuantity"
                    class="px-5 py-3 text-gray-600 hover:bg-blue-50 hover:text-blue-600 rounded-l-xl transition-all duration-300 border-r border-gray-300">
                    <i class="bi bi-dash-lg text-lg font-bold"></i>
                  </button>
                  <span class="px-8 py-3 text-gray-900 font-bold text-lg min-w-[80px] text-center bg-gray-50">{{ quantity }}</span>
                  <button @click="increaseQuantity"
                    class="px-5 py-3 text-gray-600 hover:bg-blue-50 hover:text-blue-600 rounded-r-xl transition-all duration-300 border-l border-gray-300">
                    <i class="bi bi-plus-lg text-lg font-bold"></i>
                  </button>
                </div>
                <div class="flex items-center gap-2 text-gray-600 bg-gray-50 px-4 py-2 rounded-lg border border-gray-200">
                  <i class="bi bi-box text-green-500"></i>
                  <span>库存：<span class="text-green-600 font-bold">{{ product.stockCount }}</span> 件</span>
                </div>
              </div>
            </div>

            <!-- 未登录提示 -->
            <div v-if="!userStore.isLoggedIn"
              class="mb-6 p-4 bg-yellow-50 border border-yellow-200 rounded-xl">
              <div class="flex items-center gap-2 text-yellow-700 mb-2">
                <i class="bi bi-info-circle"></i>
                <span class="font-medium">购买提示</span>
              </div>
              <p class="text-yellow-700 text-sm">
                <NuxtLink to="/auth/login" class="text-yellow-600 hover:text-yellow-800 underline font-medium">登录
                </NuxtLink>
                后即可将商品添加到购物车，享受更便捷的购物体验。
              </p>
            </div>

            <!-- 购买按钮 -->
            <div class="space-y-4 mb-8">
              <button @click="addToCart"
                :disabled="!product.inStock || showSuccessMessage || isAddingToCart || !userStore.isLoggedIn"
                data-add-to-cart
                class="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white py-4 px-6 rounded-xl font-bold text-lg transition-all duration-300 flex items-center justify-center gap-3 shadow-lg hover:shadow-xl disabled:cursor-not-allowed transform hover:-translate-y-1 active:translate-y-0">
                <div v-if="isAddingToCart"
                  class="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                <i v-else class="bi bi-cart-plus text-xl"></i>
                <span v-if="!userStore.isLoggedIn">请先登录</span>
                <span v-else-if="!product.inStock">暂时缺货</span>
                <span v-else-if="isAddingToCart">添加中...</span>
                <span v-else>加入购物车</span>
              </button>

              <button @click="buyNow" :disabled="!product.inStock || !userStore.isLoggedIn"
                class="w-full bg-green-600 hover:bg-green-700 disabled:bg-gray-400 text-white py-4 px-6 rounded-xl font-bold text-lg transition-all duration-300 flex items-center justify-center gap-3 shadow-lg hover:shadow-xl disabled:cursor-not-allowed transform hover:-translate-y-1 active:translate-y-0">
                <i class="bi bi-lightning-fill text-xl"></i>
                <span v-if="!userStore.isLoggedIn">请先登录</span>
                <span v-else>立即购买</span>
              </button>
            </div>

            <!-- 保障信息 -->
            <div class="pt-6 border-t border-gray-200">
              <div class="grid grid-cols-3 gap-4 text-center">
                <div class="flex flex-col items-center gap-3 p-4 bg-green-50 rounded-xl border border-green-100 hover:border-green-200 transition-all duration-300 group">
                  <div class="p-3 bg-green-100 rounded-full group-hover:scale-110 transition-transform duration-300">
                    <i class="bi bi-truck text-2xl text-green-600"></i>
                  </div>
                  <span class="text-sm text-gray-700 font-medium">免费配送</span>
                </div>
                <div class="flex flex-col items-center gap-3 p-4 bg-blue-50 rounded-xl border border-blue-100 hover:border-blue-200 transition-all duration-300 group">
                  <div class="p-3 bg-blue-100 rounded-full group-hover:scale-110 transition-transform duration-300">
                    <i class="bi bi-shield-check text-2xl text-blue-600"></i>
                  </div>
                  <span class="text-sm text-gray-700 font-medium">两年保修</span>
                </div>
                <div class="flex flex-col items-center gap-3 p-4 bg-purple-50 rounded-xl border border-purple-100 hover:border-purple-200 transition-all duration-300 group">
                  <div class="p-3 bg-purple-100 rounded-full group-hover:scale-110 transition-transform duration-300">
                    <i class="bi bi-arrow-repeat text-2xl text-purple-600"></i>
                  </div>
                  <span class="text-sm text-gray-700 font-medium">30天退换</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 详细规格 -->
      <div class="bg-white rounded-2xl border border-gray-200 shadow-lg p-8 mb-12">
        <h2 class="text-3xl font-bold text-gray-900 mb-8 flex items-center gap-4">
          <div class="p-3 bg-orange-100 rounded-lg">
            <i class="bi bi-gear-fill text-orange-600 text-2xl"></i>
          </div>
          <span>技术规格</span>
        </h2>
        <div v-if="product.specs && Object.keys(product.specs).length > 0" class="grid md:grid-cols-2 gap-6">
          <div v-for="(value, key) in product.specs" :key="key"
            class="group flex justify-between items-center p-5 bg-gray-50 rounded-xl border border-gray-100 hover:border-blue-200 hover:bg-blue-50 transition-all duration-300">
            <span class="text-gray-700 font-semibold text-lg">{{ translateSpecKey(key) }}</span>
            <span class="font-bold text-gray-900 text-lg group-hover:text-blue-700 transition-colors duration-300">{{ value }}</span>
          </div>
        </div>
        <div v-else class="text-center py-8">
          <i class="bi bi-info-circle text-3xl mb-2 text-gray-400"></i>
          <p class="text-gray-500">暂无规格信息</p>
        </div>
      </div>

      <!-- 用户评价 -->
      <div class="bg-white rounded-2xl border border-gray-200 shadow-lg p-8">
        <h2 class="text-3xl font-bold text-gray-900 mb-8 flex items-center gap-4">
          <div class="p-3 bg-yellow-100 rounded-lg">
            <i class="bi bi-chat-dots-fill text-yellow-600 text-2xl"></i>
          </div>
          <span>用户评价</span>
        </h2>

        <!-- 评价统计 -->
        <div v-if="reviewStats" class="grid md:grid-cols-2 gap-8 mb-8">
          <div class="text-center p-6 bg-yellow-50 rounded-xl border border-yellow-100">
            <div class="text-6xl font-bold text-yellow-600 mb-4">
              {{ reviewStats.average_rating }}</div>
            <div class="flex justify-center mb-4">
              <i v-for="i in 5" :key="i"
                :class="i <= Math.round(reviewStats.average_rating) ? 'text-yellow-400' : 'text-gray-300'"
                class="bi bi-star-fill text-2xl"></i>
            </div>
            <div class="text-gray-700 text-lg">基于 <span class="text-yellow-600 font-bold">{{ reviewStats.total_reviews }}</span> 条评价</div>
          </div>

          <div class="space-y-4">
            <div v-for="item in reviewStats.rating_distribution" :key="item.rating" class="flex items-center gap-4">
              <span class="text-gray-900 w-12 flex-shrink-0 font-bold">{{ item.rating }}星</span>
              <div class="flex-1 bg-gray-200 rounded-full h-3 overflow-hidden">
                <div class="bg-yellow-400 h-3 rounded-full transition-all duration-500"
                  :style="{ width: `${item.percentage}%` }"></div>
              </div>
              <span class="text-gray-600 w-16 text-sm flex-shrink-0 font-medium">{{ item.count }} 条</span>
            </div>
          </div>
        </div>

        <!-- 加载中状态 -->
        <div v-else-if="isLoadingReviews" class="text-center py-8">
          <div class="w-8 h-8 border-2 border-yellow-400 border-t-transparent rounded-full animate-spin mx-auto mb-4">
          </div>
          <p class="text-gray-600">正在加载评论统计...</p>
        </div>

        <!-- 发表评论组件 -->
        <div class="mb-8">
          <ReviewForm v-if="product" :product-id="product.id" @review-submitted="handleReviewSubmitted" />
        </div>

        <!-- 评论筛选和排序 -->
        <div class="flex flex-wrap gap-4 mb-6">
          <select v-model="reviewFilters.rating" @change="handleFilterChange"
            class="px-4 py-2 bg-white border border-gray-300 rounded-lg text-gray-900 focus:ring-2 focus:ring-blue-500">
            <option value="all">所有评分</option>
            <option value="5">5星</option>
            <option value="4">4星</option>
            <option value="3">3星</option>
            <option value="2">2星</option>
            <option value="1">1星</option>
          </select>

          <select v-model="reviewFilters.sort" @change="handleFilterChange"
            class="px-4 py-2 bg-white border border-gray-300 rounded-lg text-gray-900 focus:ring-2 focus:ring-blue-500">
            <option value="newest">最新发布</option>
            <option value="oldest">最早发布</option>
            <option value="rating_high">评分从高到低</option>
            <option value="rating_low">评分从低到高</option>
            <option value="helpful">最有帮助</option>
          </select>
        </div>

        <!-- 评价列表 -->
        <div v-if="!isLoadingReviews && reviews.length > 0" class="space-y-6">
          <div v-for="review in reviews" :key="review.id"
            class="p-6 bg-gray-50 rounded-xl border border-gray-100 hover:border-blue-200 hover:bg-blue-50 transition-all duration-300">
            <div class="flex items-center justify-between mb-4">
              <div class="flex items-center gap-4">
                <!-- 用户头像 -->
                <div class="w-14 h-14 bg-blue-100 rounded-full flex items-center justify-center border border-blue-200 overflow-hidden">
                  <img v-if="review.user_info?.avatar && !review.is_anonymous" :src="review.user_info.avatar"
                    :alt="review.author" class="w-full h-full object-cover">
                  <i v-else class="bi bi-person-fill text-blue-600 text-xl"></i>
                </div>
                <div>
                  <div class="flex items-center gap-2">
                    <!-- 显示用户名或匿名 -->
                    <div class="font-bold text-gray-900 text-lg">
                      {{ review.is_anonymous ? '匿名用户' : (review.user_info?.nickname || review.author) }}
                    </div>
                    <!-- 匿名标识 -->
                    <span v-if="review.is_anonymous"
                      class="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-full border border-gray-200">
                      <i class="bi bi-incognito mr-1"></i>
                      匿名
                    </span>
                    <!-- 已验证购买标识 -->
                    <span v-if="review.verified_purchase"
                      class="px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full border border-green-200">
                      <i class="bi bi-check-circle mr-1"></i>
                      已购买
                    </span>
                  </div>
                  <div class="text-sm text-gray-500">{{ formatDate(review.created_at) }}</div>
                </div>
              </div>
              <div class="flex gap-1">
                <i v-for="i in 5" :key="i" :class="i <= review.rating ? 'text-yellow-400' : 'text-gray-300'"
                  class="bi bi-star-fill text-lg"></i>
              </div>
            </div>
            <p class="text-gray-700 leading-relaxed text-lg mb-4">{{ review.comment }}</p>

            <!-- 评论图片 -->
            <div v-if="review.images && review.images.length > 0" class="grid grid-cols-3 gap-2 mb-4">
              <img v-for="(image, index) in review.images" :key="index" :src="image" :alt="`评论图片${index + 1}`"
                class="w-full h-20 object-cover rounded-lg border border-gray-200">
            </div>

            <!-- 点赞功能 -->
            <div class="flex items-center justify-between pt-4 border-t border-gray-200">
              <span class="text-gray-500 text-sm">这条评论有帮助吗？</span>
              <div class="flex items-center gap-4">
                <button @click="toggleReviewHelpful(review.id, true)"
                  class="flex items-center gap-2 px-3 py-1 text-gray-500 hover:text-green-600 transition-colors duration-200">
                  <i class="bi bi-hand-thumbs-up"></i>
                  <span>有帮助 ({{ review.helpful_count || 0 }})</span>
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 无评论状态 -->
        <div v-else-if="!isLoadingReviews && reviews.length === 0" class="text-center py-12">
          <div class="text-4xl text-gray-400 mb-4">
            <i class="bi bi-chat-dots"></i>
          </div>
          <h3 class="text-xl font-semibold text-gray-900 mb-2">暂无评论</h3>
          <p class="text-gray-500 mb-6">成为第一个评价此产品的用户</p>
        </div>

        <!-- 评论加载中 -->
        <div v-else-if="isLoadingReviews" class="text-center py-8">
          <div class="w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin mx-auto mb-4">
          </div>
          <p class="text-gray-600">正在加载评论...</p>
        </div>

        <!-- 评论分页 -->
        <div v-if="!isLoadingReviews && reviews.length > 0" class="mt-8 flex justify-center">
          <div class="flex items-center gap-2">
            <button @click="goToPage(currentPage - 1)" :disabled="currentPage <= 1"
              class="px-4 py-2 bg-white border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200">
              <i class="bi bi-chevron-left"></i>
              上一页
            </button>

            <span class="px-4 py-2 text-gray-600">
              第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
            </span>

            <button @click="goToPage(currentPage + 1)" :disabled="currentPage >= totalPages"
              class="px-4 py-2 bg-white border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200">
              下一页
              <i class="bi bi-chevron-right"></i>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error && !loading" class="container mx-auto px-6 py-20 relative">
      <div class="text-center">
        <div class="inline-flex flex-col items-center bg-white rounded-2xl border border-red-200 p-16 shadow-lg max-w-md mx-auto">
          <div class="text-8xl text-red-500 mb-8">
            <i class="bi bi-exclamation-triangle-fill"></i>
          </div>
          <h3 class="text-3xl font-bold text-gray-900 mb-4">加载失败</h3>
          <p class="text-gray-600 text-lg mb-8">{{ error }}</p>
          <div class="space-y-3 w-full">
            <button @click="loadProductDetail"
              class="w-full bg-blue-600 hover:bg-blue-700 text-white py-3 px-6 rounded-xl font-semibold transition-colors duration-300">
              <i class="bi bi-arrow-clockwise mr-2"></i>
              重新加载
            </button>
            <button @click="$router.go(-1)"
              class="w-full border border-gray-300 hover:border-blue-300 text-gray-700 hover:text-blue-600 hover:bg-blue-50 py-3 px-6 rounded-xl font-semibold transition-all duration-300">
              返回上页
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-else-if="loading" class="container mx-auto px-6 py-20 relative">
      <div class="text-center">
        <div class="inline-flex flex-col items-center bg-white rounded-2xl border border-gray-200 p-16 shadow-lg">
          <div class="relative mb-8">
            <div class="w-20 h-20 border-4 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
            <div class="absolute inset-0 w-20 h-20 border-4 border-blue-200 rounded-full animate-pulse"></div>
          </div>
          <p class="text-3xl font-bold text-gray-900 mb-4">正在加载产品详情...</p>
          <p class="text-gray-600 text-lg">请稍候，正在为您获取最新信息</p>
        </div>
      </div>
    </div>

    <!-- 购买成功提示 -->
    <div v-if="showSuccessMessage"
      class="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <div class="bg-white rounded-2xl border border-gray-200 shadow-2xl p-10 max-w-md w-full text-center transform animate-bounce-in">
        <div class="text-8xl text-green-500 mb-8 relative">
          <i class="bi bi-check-circle-fill"></i>
        </div>
        <h3 class="text-3xl font-bold text-gray-900 mb-6">已加入购物车！</h3>
        <p class="text-gray-600 mb-8 text-lg leading-relaxed">{{ product?.name }} 已成功添加到购物车。</p>
        <div class="space-y-4">
          <button @click="goToCheckout"
            class="w-full bg-green-600 hover:bg-green-700 text-white py-3 px-6 rounded-xl font-bold text-lg transition-colors duration-300">
            立即去结算
          </button>
          <button @click="hideSuccessMessage"
            class="w-full border border-gray-300 hover:border-green-300 text-gray-700 hover:text-green-600 hover:bg-green-50 py-3 px-6 rounded-xl font-bold text-lg transition-all duration-300">
            继续购物
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup >
// 导入路由参数
const route = useRoute()
const productId = parseInt(route.params.id)
// 导入API和stores
import { productsApi } from '~/utils/api'
import { cartApi } from '~/utils/api/cart'
import { reviewsApi } from '~/utils/api/reviews'
import { useUserStore } from '~/stores/user'
import { createDiscreteApi } from 'naive-ui'
import ReviewForm from '~/components/ReviewForm.vue'

// 使用stores
const userStore = useUserStore()

// 创建消息API
const { message } = createDiscreteApi(['message'])

// 响应式数据
const product = ref(null)
const quantity = ref(1)
const isFavorite = ref(false)
const showSuccessMessage = ref(false)
const loading = ref(true)
const error = ref(null)
const isAddingToCart = ref(false)

// 评论相关数据
const reviews = ref([])
const reviewStats = ref(null)
const isLoadingReviews = ref(false)
const currentPage = ref(1)
const totalPages = ref(1)
const pageSize = 5 // 每页显示5条评论
const reviewFilters = ref({
  rating: 'all',
  sort: 'newest'
})

// 撒花批次管理
const confettiBatches = ref([])
let confettiInterval = null

// 获取产品类别
const getProductCategory = (category) => {
  const categories = {
    graphics: '显卡',
    cpu: '处理器',
    motherboard: '主板',
    power: '电源',
    memory: '内存',
    storage: '存储',
    monitor: '显示器',
    case: '机箱',
    cooler: '散热器'
  }
  return categories[category] || '硬件'
}

// 加载评论数据
const loadReviews = async () => {
  if (!product.value) return

  try {
    isLoadingReviews.value = true

    // 获取评论列表
    const reviewsResponse = await reviewsApi.getProductReviews(product.value.id, {
      page: currentPage.value,
      limit: pageSize,
      rating: reviewFilters.value.rating === 'all' ? undefined : parseInt(reviewFilters.value.rating),
      sort: reviewFilters.value.sort
    })

    if (reviewsResponse.success) {
      reviews.value = reviewsResponse.data.reviews
      // 更新分页信息
      totalPages.value = reviewsResponse.data.pagination.total_pages
    }

    // 获取评论统计
    const statsResponse = await reviewsApi.getProductReviewStats(product.value.id)
    if (statsResponse.success) {
      reviewStats.value = statsResponse.data
    }
  } catch (err) {
    console.error('加载评论失败:', err)
  } finally {
    isLoadingReviews.value = false
  }
}

// 分页导航
const goToPage = async (page) => {
  if (page < 1 || page > totalPages.value || page === currentPage.value) return

  currentPage.value = page
  await loadReviews()
}

// 获取产品详情
const loadProductDetail = async () => {
  try {
    loading.value = true
    error.value = null

    const response = await productsApi.getProductById(productId)

    if (response.success && response.data) {
      const apiProduct = response.data

      // 转换API数据格式为页面所需格式
      product.value = {
        id: apiProduct.id,
        name: apiProduct.name,
        brand: apiProduct.brand,
        category: getCategoryFromId(apiProduct.category_id),
        price: parseFloat(apiProduct.price),
        originalPrice: apiProduct.original_price ? parseFloat(apiProduct.original_price) : null,
        rating: parseFloat(apiProduct.rating),
        reviewCount: parseInt(apiProduct.review_count),
        viewCount: apiProduct.sales * 12 + Math.floor(Math.random() * 1000), // 模拟浏览量
        image: apiProduct.images && apiProduct.images.length > 0 ? apiProduct.images[0] : '',
        images: apiProduct.images || [],
        inStock: apiProduct.stock > 0,
        stockCount: apiProduct.stock,
        description: apiProduct.description || apiProduct.short_description,
        specs: apiProduct.specifications || {},
        features: apiProduct.features || [],
        tags: apiProduct.tags || [],
        sales: apiProduct.sales,
        slug: apiProduct.slug,
        sku: apiProduct.sku,
        model: apiProduct.model
      }

      // 检查收藏状态
      checkFavoriteStatus()

      // 加载评论数据
      await loadReviews()
    } else {
      error.value = '产品不存在或已下架'
    }
  } catch (err) {
    console.error('获取产品详情失败:', err)
    error.value = '加载产品详情时出错，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 根据分类ID获取分类名称
const getCategoryFromId = (categoryId) => {
  const categoryMap = {
    1: 'cpu',
    2: 'motherboard',
    3: 'memory',
    4: 'graphics',
    5: 'storage',
    6: 'power',
    7: 'case',
    8: 'cooler',
    9: 'monitor'
  }
  return categoryMap[categoryId] || 'hardware'
}

// 评论点赞功能
const toggleReviewHelpful = async (reviewId, helpful) => {
  if (!userStore.isLoggedIn) {
    message.warning('请先登录后再进行操作')
    return
  }

  try {
    const response = await reviewsApi.toggleReviewHelpful(reviewId, helpful)
    if (response.success) {
      // 更新本地数据
      const review = reviews.value.find(r => r.id === reviewId)
      if (review) {
        review.helpful_count += helpful ? 1 : -1
        review.helpful_count = Math.max(0, review.helpful_count)
      }
      message.success(helpful ? '点赞成功' : '取消点赞成功')
    }
  } catch (err) {
    console.error('点赞操作失败:', err)
    message.error('操作失败，请重试')
  }
}

// 处理评论提交
const handleReviewSubmitted = () => {
  // 重置到第一页并重新加载评论数据
  currentPage.value = 1
  loadReviews()

  // 显示成功消息
  message.success('感谢您的评价！评论已发布')
}

// 处理筛选器变化
const handleFilterChange = async () => {
  // 重置到第一页
  currentPage.value = 1
  await loadReviews()
}

// 检查收藏状态
const checkFavoriteStatus = () => {
  const favorites = JSON.parse(localStorage.getItem('favorites') || '[]')
  isFavorite.value = favorites.includes(productId)
}

// 方法
const increaseQuantity = () => {
  if (quantity.value < product.value?.stockCount) {
    quantity.value++
  }
}

const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

const toggleFavorite = () => {
  const favorites = JSON.parse(localStorage.getItem('favorites') || '[]')
  if (isFavorite.value) {
    const index = favorites.indexOf(productId)
    if (index > -1) favorites.splice(index, 1)
  } else {
    favorites.push(productId)
  }
  localStorage.setItem('favorites', JSON.stringify(favorites))
  isFavorite.value = !isFavorite.value
}

// 添加到购物车
const addToCart = async () => {
  if (!product.value || !product.value.inStock || showSuccessMessage.value || isAddingToCart.value) return

  // 检查用户登录状态
  if (!userStore.isLoggedIn) {
    // 未登录用户跳转到登录页面
    navigateTo('/auth/login')
    return
  }

  try {
    isAddingToCart.value = true

    const cartData = {
      productId: product.value.id,
      quantity: quantity.value
    }

    const response = await cartApi.addToCart(cartData)

    if (response.success) {
      showSuccessMessage.value = true
      playSuccessSound()

      // 显示成功消息
      console.log('商品已成功添加到购物车')
    } else {
      throw new Error(response.message || '添加到购物车失败')
    }
  } catch (err) {
    console.error('添加到购物车失败:', err)

    // 显示错误消息
    if (err.message) {
      message.error('添加失败：' + err.message)
    } else {
      message.error('添加到购物车失败，请重试')
    }
  } finally {
    isAddingToCart.value = false
  }
}

const buyNow = async () => {
  // 检查用户登录状态
  if (!userStore.isLoggedIn) {
    navigateTo('/auth/login')
    return
  }

  if (!product.value || !product.value.inStock) return

  try {
    // 直接添加到购物车并跳转到结算页面
    const cartData = {
      productId: product.value.id,
      quantity: quantity.value
    }

    const response = await cartApi.addToCart(cartData)

    if (response.success) {
      message.success('商品已添加到购物车，正在跳转到结算页面...')
      // 延迟跳转，让用户看到成功消息
      setTimeout(() => {
        navigateTo('/checkout')
      }, 1000)
    } else {
      throw new Error(response.message || '添加到购物车失败')
    }
  } catch (err) {
    console.error('立即购买失败:', err)
    message.error('购买失败：' + (err.message || '请重试'))
  }
}

const goToCheckout = () => {
  navigateTo('/checkout')
}

// 隐藏成功消息
const hideSuccessMessage = () => {
  showSuccessMessage.value = false
}

// 播放成功音效（可选）
const playSuccessSound = () => {
  try {
    // 创建Web Audio API音效
    const audioContext = new (window.AudioContext || window.webkitAudioContext)()
    const oscillator = audioContext.createOscillator()
    const gainNode = audioContext.createGain()

    oscillator.connect(gainNode)
    gainNode.connect(audioContext.destination)

    oscillator.frequency.setValueAtTime(800, audioContext.currentTime)
    oscillator.frequency.setValueAtTime(1000, audioContext.currentTime + 0.1)
    oscillator.frequency.setValueAtTime(1200, audioContext.currentTime + 0.2)

    gainNode.gain.setValueAtTime(0, audioContext.currentTime)
    gainNode.gain.linearRampToValueAtTime(0.1, audioContext.currentTime + 0.01)
    gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3)

    oscillator.start(audioContext.currentTime)
    oscillator.stop(audioContext.currentTime + 0.3)
  } catch (error) {
    // 音效播放失败时静默处理
    console.log('音效播放不支持或被禁用')
  }
}

// 监听成功消息状态，管理撒花动画
watch(showSuccessMessage, (newValue) => {
  if (newValue) {
    // 开始撒花动画
    startConfettiAnimation()

    // 撒花动画3秒后自动停止，但弹窗保持显示
    setTimeout(() => {
      stopConfettiAnimation()
    }, 3000)
  } else {
    // 停止撒花动画
    stopConfettiAnimation()
  }
})

// 开始撒花动画
const startConfettiAnimation = () => {
  confettiBatches.value = []
  let batchId = 0

  // 立即生成第一批撒花
  confettiBatches.value.push({
    id: batchId++,
    delay: 0
  })

  // 每0.5秒生成新的撒花批次，让动画更连续
  confettiInterval = setInterval(() => {
    confettiBatches.value.push({
      id: batchId++,
      delay: 0
    })

    // 保持最多6个批次，移除旧的批次
    if (confettiBatches.value.length > 6) {
      confettiBatches.value.shift()
    }
  }, 500)
}

// 停止撒花动画
const stopConfettiAnimation = () => {
  if (confettiInterval) {
    clearInterval(confettiInterval)
    confettiInterval = null
  }
  confettiBatches.value = []
}

// 生成撒花颜色
const getConfettiColor = (index) => {
  const vibrantColors = [
    '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
    '#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9',
    '#F8C471', '#82E0AA', '#F1948A', '#85C1E9', '#F9E79F',
    '#AED6F1', '#A9DFBF', '#F5B7B1', '#D7BDE2', '#A3E4D7',
    '#FFD93D', '#6BCF7F', '#4D96FF', '#9B59B6', '#1ABC9C',
    '#E74C3C', '#F39C12', '#8E44AD', '#27AE60', '#3498DB'
  ]
  return vibrantColors[index % vibrantColors.length]
}

// 获取撒花形状
const getConfettiShape = (index) => {
  const shapes = ['confetti-circle', 'confetti-square', 'confetti-triangle']
  return shapes[index % shapes.length]
}

const translateSpecKey = (key) => {
  const translations = {
    'TDP': 'TDP功耗',
    '制程': '制程工艺',
    '插槽': '接口插槽',
    '缓存': '缓存',
    'L2缓存': 'L2缓存',
    'L3缓存': 'L3缓存',
    '核心数': '核心数',
    '线程数': '线程数',
    '内存支持': '支持内存',
    '基础频率': '基础频率',
    '最大睿频': '最大睿频',
    '最大加速频率': '最大加速',
    '功耗': '功耗',
    '接口': '显示接口',
    '显存': '显存容量',
    '架构': '架构',
    'CUDA核心': 'CUDA核心',
    '加速频率': '加速频率',
    '显存位宽': '显存位宽',
    '流处理器': '流处理器',
    '游戏频率': '游戏频率',
    '容量': '容量',
    '散热': '散热方案',
    '时序': '时序',
    '电压': '工作电压',
    '质保': '质保期',
    '频率': '工作频率',
    '兼容性': '平台兼容'
  }
  return translations[key] || key
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// 页面加载时获取产品详情
onMounted(() => {
  loadProductDetail()
})

// 页面卸载时清理定时器
onUnmounted(() => {
  stopConfettiAnimation()
})

// 监听路由变化
watch(() => route.params.id, () => {
  const newProductId = parseInt(route.params.id)
  if (newProductId !== productId) {
    loadProductDetail()
  }
})

// 页面元数据
useHead({
  title: computed(() => product.value ? `${product.value.name} - xlCig` : '产品详情 - xlCig'),
  meta: [
    { name: 'description', content: computed(() => product.value?.description || '查看产品详细信息和技术规格') }
  ]
})

// 生成撒花样式
const getConfettiStyle = (index, batchDelay) => {
  // 创建圆形扩散效果
  const angle = (index * 12) % 360 // 每个撒花不同角度
  const radiusMultiplier = 0.5 + Math.random() * 0.5 // 随机半径

  // 计算扩散方向
  const radians = (angle * Math.PI) / 180
  const endX = 50 + Math.cos(radians) * radiusMultiplier * 80 // 从中心扩散
  const endY = 45 + Math.sin(radians) * radiusMultiplier * 60 // 从中心扩散

  // 确保撒花在视窗内
  const clampedEndX = Math.max(5, Math.min(95, endX))
  const clampedEndY = Math.max(10, Math.min(90, endY))

  return {
    '--start-x': '50%',
    '--start-y': '42%', // 弹窗底部中心
    '--end-x': clampedEndX + '%',
    '--end-y': clampedEndY + '%',
    '--rotation': (Math.random() * 720 - 360) + 'deg',
    animationDelay: (Math.random() * 1.2 + batchDelay) + 's',
    animationDuration: (2.5 + Math.random() * 1.5) + 's',
    backgroundColor: getConfettiColor(index),
    width: (10 + Math.random() * 8) + 'px',
    height: (10 + Math.random() * 8) + 'px',
    boxShadow: `0 0 ${8 + Math.random() * 8}px rgba(255, 255, 255, 0.8)`
  }
}
</script>

<style scoped>
/* 产品图片容器 */
.product-image-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 产品Placeholder样式 */
.product-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(147, 51, 234, 0.05) 100%);
  padding: 2rem;
  text-align: center;
  position: relative;
  overflow: hidden;
}

/* 产品图标包装器 */
.product-icon-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-placeholder-text {
  font-size: 1.25rem;
  font-weight: 700;
  color: #374151;
  text-align: center;
  line-height: 1.4;
  max-width: 85%;
}

/* 成功提示动画 */
@keyframes bounce-in {
  0% {
    transform: scale(0.3) rotate(-5deg);
    opacity: 0;
  }
  50% {
    transform: scale(1.05) rotate(2deg);
  }
  70% {
    transform: scale(0.95) rotate(-1deg);
  }
  100% {
    transform: scale(1) rotate(0deg);
    opacity: 1;
  }
}

.animate-bounce-in {
  animation: bounce-in 0.6s ease-out forwards;
}

/* 悬停效果 */
.group:hover .group-hover\:scale-110 {
  transform: scale(1.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-placeholder-text {
    font-size: 1rem;
    max-width: 90%;
  }
}
</style>